<template>
  <div class="home">
    <div class="home-video">
      <video ref="video"></video>
    </div>
    <div class="home-list">
      <!-- 添加按钮 -->
      <div @click="isJia" class="home-list-left" v-if="picList.length > 0">
        <!-- <img src="../assets/jia.png" alt="" /> -->
      </div>
      <!-- 图片列表 -->
      <div class="home-list-item" v-for="item in picList" :key="item.url">
        <img
          @click="isPreview(item)"
          v-if="item.type == 1"
          :src="item.url"
          alt=""
        />
        <div class="video-container" v-if="item.type == 2">
          <video :src="item.url" autoplay loop></video>
          <span @click="isPreview(item)"></span>
        </div>
      </div>
      <!-- 删除按钮 -->
      <div @click="isShan" class="home-list-right" v-if="picList.length > 0">
        <!-- <img src="../assets/shan.png" alt="" /> -->
      </div>
    </div>
    <p
      :style="{ opacity: picList.length > 0 ? '0' : '1' }"
      style="
        font-size: 15px;
        color: #6aa17f;
        text-align: center;
        line-height: 30px;
      "
    >
      按住拍摄 点击拍照
    </p>
    <div class="home-footer">
      <div class="home-but-tool">
        <input type="file" accept="image/*" />
        <!-- <img src="../assets/docum.png" alt="" /> -->
      </div>
      <div class="home-but" @touchstart="photosStart" @touchend="photosEnd">
        <Circle
          v-model:current-rate="currentRate"
          color="#FF9719"
          layer-color="#E9E9E9"
          size="80px"
          :rate="currentNum"
          :stroke-width="30"
        />
        <span></span>
      </div>
      <div class="home-but-tool">
        <!-- <img @click="isDirec" src="../assets/ado.png" alt="" /> -->
      </div>
    </div>
    <canvas
      width="800"
      height="800"
      style="width: 100%; height: 50vh; opacity: 0"
      id="canvasCamera"
    ></canvas>
  </div>
  <!-- 预览弹窗 -->
  <div class="preview" v-if="imgShow">
    <div class="preview-content">
      <img v-if="contents.type == 1" :src="contents.url" alt="" />
      <video
        v-if="contents.type == 2"
        :src="contents.url"
        controls
        autoplay
      ></video>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { showFailToast, showSuccessToast } from "vant";
import { useRouter } from "vue-router";

let router = useRouter();

// 获取 video 视频标签
let video = ref("");
// 摄像头对象
let mediaStreamTrack = ref("");
// 摄像头数据流
let video_stream = ref("");
// 画布标签
let canvas = "";
// 画布实例对象
let context = "";
// 拍摄的图片base64路径
let picList = ref(
  sessionStorage.getItem("list")
    ? JSON.parse(sessionStorage.getItem("list"))
    : []
);
setTimeout(() => {
  sessionStorage.removeItem("list");
}, 500);
// 按钮进度条初始位置
const currentRate = ref(0);
// 按钮进度条进度
const currentNum = ref(0);
// 摄像头方向
let direc = sessionStorage.getItem("direc")
  ? sessionStorage.getItem("direc")
  : "user";
// 预览弹窗显示状态
let imgShow = ref(false);
// 预览内容
let contents = ref({});

// 页面挂载成功
onMounted(() => {
  // 调用摄像头
  getCamera();
  // 生成画布
  canvas = document.getElementById("canvasCamera");
  context = canvas.getContext("2d");
});

// 获取手机摄像头事件
const getCamera = () => {
  console.log(direc);
  // 判断该浏览器是否支持 mediaDevices API
  if (navigator.mediaDevices === undefined) {
    navigator.mediaDevices = {};
    showFailToast("浏览器版本太低！");
    return;
  }
  // 获取手机摄像头
  navigator.mediaDevices
    .getUserMedia({
      video: { facingMode: direc },
      audio: false,
    })
    .then((stream) => {
      // 摄像头开启成功
      mediaStreamTrack.value =
        typeof stream.stop === "function" ? stream : stream.getTracks()[0];
      video_stream.value = stream;
      video.value.srcObject = stream;
      video.value.play();
    })
    .catch((err) => {
      console.log(err);
      showFailToast("请打开摄像头权限");
    });
};

// 切换摄像头
const isDirec = () => {
  // 判断是否在预览
  if (imgShow.value) {
    showFailToast("请点击加号切换到拍摄页面");
    return;
  }
  if (direc == "environment") {
    sessionStorage.setItem("direc", "user");
  } else {
    sessionStorage.setItem("direc", "environment");
  }
  sessionStorage.setItem("list", JSON.stringify(picList.value));
  router.go(0);
};

// 预览图片视频
const isPreview = (item) => {
  console.log(item);
  imgShow.value = true;
  contents.value = item;
};

// 切换到拍摄
const isJia = () => {
  imgShow.value = false;
};

// 删除
const isShan = () => {
  // 判断是否在预览
  if (!imgShow.value) {
    showFailToast("请选择要删除的内容");
    return;
  }
  for (let i = 0; i < picList.value.length; i++) {
    if (picList.value[i].url == contents.value.url) {
      picList.value.splice(i, 1);
    }
  }
  imgShow.value = false;
  sessionStorage.setItem("list", JSON.stringify(picList.value));
};

// 检测点击按钮事件定时器
let times = null;

// 用户是否长按 false 点击、ture 长按
let userStatus = ref(false);

// 手指点击触发
const photosStart = () => {
  // 判断是否在预览
  if (imgShow.value) {
    showFailToast("请点击加号，切换到拍摄页面");
    return;
  }
  // 判断是否超过5个
  if (picList.value.length >= 5) {
    showFailToast("最多录制5个录像!");
    return;
  }
  times = setTimeout(() => {
    userStatus.value = true;
    pressEvenet();
  }, 500);
};

// 手指离开触发
const photosEnd = () => {
  // 判断是否在预览
  if (imgShow.value) {
    return;
  }
  // 判断是否超过5个
  if (picList.value.length >= 5) {
    return;
  }
  if (userStatus.value) {
    // 暂停录制
    pressStop();
    userStatus.value = false;
  } else {
    // 执行点击事件
    clickEvent();
    clearTimeout(times);
  }
};

// 点击触发的事件
const clickEvent = () => {
  currentNum.value = 0;
  // 将照片渲染到canvas画布上
  // context.drawImage(video.value, 0, 0, canvas.offsetWidth / 1.2, canvas.offsetHeight / 2.5);
  context.drawImage(video.value, 0, 0, 800, 800);
  // 将画布转为base64图片格式
  const image = canvas.toDataURL("image/png");
  picList.value.push({
    type: 1,
    url: image,
  });
};

// 长按触发的事件
let mediaRecorder = null;
let inte = null;
let eouts = null;
let stops = false;
const pressEvenet = () => {
  currentNum.value = 0;
  let chunks = [];
  stops = true;
  mediaRecorder = new MediaRecorder(video_stream.value, {
    mimeType: "video/webm;codecs=vp9",
  });
  mediaRecorder.ondataavailable = (event) => {
    if (event.data && event.data.size > 0) {
      chunks.push(event.data);
    }
  };
  mediaRecorder.onstop = () => {
    const blob = new Blob(chunks, { type: "video/webm" });
    const url = URL.createObjectURL(blob);
    console.log(url);
    // const link = document.createElement("a");
    // link.href = url;
    // link.download = "video.webm";
    // link.click();
    // URL.revokeObjectURL(url);
    picList.value.push({
      type: 2,
      url: url,
    });
    chunks = [];
  };
  mediaRecorder.start();
  inte = setInterval(() => {
    currentNum.value++;
  }, 200);
  eouts = setTimeout(() => {
    clearInterval(inte);
    showSuccessToast("录制完成");
    mediaRecorder.stop();
    stops = false;
  }, 20000);
};

// 停止录制事件
const pressStop = () => {
  if (stops) {
    mediaRecorder.stop();
    showSuccessToast("录制完成");
    stops = false;
    clearInterval(inte);
    clearTimeout(eouts);
  }
};
</script>

<style scoped>
.home {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.home-video {
  width: 100%;
  height: 50vh;
  background-color: #eeeeee;
}

.home-video video {
  width: 100%;
  height: 100%;
  outline: none;
  /* object-fit: fill */
}

.home-footer {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 20px;
}

.home-but {
  width: 80px;
  height: 80px;
  background-color: #eaeaea;
  border-radius: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  user-select: none;
}

.home-but span {
  display: block;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  background-color: #ff981c;
  position: absolute;
}

.home-list {
  width: 100vw;
  height: 20vw;
  display: flex;
  align-items: center;
  padding: 3vw 15vw;
  position: relative;
}

.home-list-item {
  width: 12vw;
  height: 12vw;
  margin: 0 1vw;
}

.home-list-item img {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.video-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.video-container video {
  max-width: 100%;
  height: 100%;
  outline: none;
  border-radius: 8px;
  object-fit: fill;
}

.video-container span {
  display: block;
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 10;
}

.home-list-left {
  position: absolute;
  left: 0;
  top: 0;
  width: 15vw;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-list-left img {
  width: 32px;
  height: 32px;
}

.home-list-right {
  position: absolute;
  right: 0;
  top: 0;
  width: 15vw;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-list-right img {
  width: 32px;
  height: 32px;
}

.home-but-tool {
  width: 100px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-but-tool img {
  width: 36px;
}

.home-but-tool {
  width: 100px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.home-but-tool input {
  width: 36px;
  height: 36px;
  position: absolute;
  z-index: 1;
  opacity: 0;
}

.preview {
  width: 100%;
  height: 50vh;
  background-color: #ffffff;
  position: absolute;
  top: 0;
  z-index: 100;
}

.preview-content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-content img {
  width: 74%;
  height: 50vh;
  border-radius: 8px;
}

.preview-content video {
  width: 74%;
  outline: none;
  border-radius: 8px;
}
</style>
